<?php
/**
 * Created by PhpStorm.
 * User: fangfc
 * Date: 2019/4/9
 * Time: 19:14
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class Role extends AdminController
{
    public function role_list()
    {
//        $sql = 'SELECT `ro`.`id`, `ro`.`name`,`ru`.`name` as `rule_name`, `ro`.`comment`
//                FROM `role` as `ro`
//                LEFT JOIN `role_rule` AS `roru` ON (`ro`.id = `roru`.`roid`)
//                LEFT JOIN `rule` AS `ru` ON(`ru`.`id` = `roru`.`ruid`)';

//        $res = Db::table('free_role')
//            ->alias('ro')
//            ->field('`ro`.`id`, `ro`.`name`,`ru`.`name` as `rule_name`, `ro`.`comment`')
//            ->join('role_rule roru', 'ro.id = roru.roid', $type="LEFT")
//            ->join('rule ru', 'roru.id = ru.id', $type="LEFT")
//            ->select();

        $res = Db::name('role')
            ->field('id, name, comment, status')
            ->paginate();
        $page = $res->render();
        $data = array();

        for($i = 0; $i<count($res); $i++) {
            $data[$i] = $res[$i];
            $rules = Db::name('role_rule')
                ->field('ru.rule, ru.id')
                ->alias('rr')
                ->field('')
                ->join('rule ru', 'rr.ruid = ru.id')
                ->where('rr.roid', $res[$i]['id'])
                ->select();
            $data[$i]['rules'] = $rules;
        }

//        $data = array();
//        // 此处合并数据
//        foreach($res as $k => $v){
//            $data[$v['id']]['name'] = $v['name'];
//            $data[$v['id']]['id'] = $v['id'];
//            $data[$v['id']]['comment'] = $v['comment'];
//            $data[$v['id']]['rules'][] = $v['rule_name'];
//        }


        $this->assign('page', $page);
        $this->assign('data', $data);
        return $this->fetch('page/role_list');
    }

    // 添加角色页面
    public function role_add_page()
    {
        $data = Db::name('rule')
            ->field('id, name, category, rule')
            ->select();
        $this->assign('data', $data);
        return $this->fetch('page/role_add');
    }

    // 添加角色
    public function role_add()
    {
        $name = $_POST['name'];
        $comment = $_POST['desc'];
        $status = 1;                    // 待修改
        // $sql =  "INSERT INTO `role`(`name`, `comment`, `status`) VALUES('{$name}', '{$comment}', '{$status}')";
        $data = array('name' => $name, 'comment' => $comment, 'status' => $status);
        $res = Db::name('role')->insert($data);
        if ($res) {
            $lastId = Db::name('role')->getLastInsID();
        }else{
            return "插入失败";
        }
        $data = array();
        foreach($_POST['ruid'] as $v) {
            $data[] = array('roid' => $lastId, 'ruid' => $v);
        }
        $res = Db::name('role_rule')->insertAll($data);

        if ($res) {
            return "添加成功";
        }else{
            return "添加失败";
        }
    }

    /**
     * 展现角色修改界面
     *
     * @access public
     * @param int   $id     roleId
     * @return view 模板
     */
    public function role_edit($id)
    {
        $data = array();
        $res = Db::table('free_role')
            ->alias('ro')
            ->field('ro.id as roid, ro.name as roname, ru.id as ruid, ru.name as runame, ro.comment')
            ->join('role_rule rr', 'ro.id = rr.roid', $type = 'LEFT')
            ->join('rule ru', 'rr.ruid = ru.id', $type = 'LEFT')
            ->where('ro.id', $id)
            ->select();

        foreach($res as $k => $v){
            $data['id'] = $v['roid'];
            $data['name'] = $v['roname'];
            $data['comment'] = $v['comment'];
            $data['rules'][$v['ruid']] = $v['runame'];
        }
        $allRule = Db::name('rule')->select();
        $data['allRule'] = $allRule;
        $this->assign('role', $data);
        return $this->fetch('page/role_edit');
    }

    /**
     * 修改角色信息
     *
     * @access public
     * @return view 模板
     */
    public function update()
    {
        $id = $_POST['id'];
        $name =$_POST['name'];
        $rules = $_POST['ruleId'];
        $comment = $_POST['desc'];
        $data = array();

        $upRes = Db::name('role')->where('id', $id)->update(['name' => $name, 'comment' => $comment]);
        $delRes = Db::name('role_rule')
            ->where('roid', $id)
            ->delete();
        foreach ($rules as $ruleId) {
            $data[] = array('roid' => $id, 'ruid' => $ruleId);
        }
        $insRes = Db::name('role_rule')->insertAll($data);
        if ($delRes || $insRes || $upRes ) {
            return "修改成功";
        }
        return "修改失败";

    }

    // 删除角色
    public function remove()
    {
        $res1 = Db::table('free_role')
            ->where('id', $_GET['id'])
            ->delete();
        // 联动删除role_rule
        $res2 = Db::table('free_role_rule')
            ->where('roid', $_GET['id'])
            ->delete();

        if ($res1 || $res2) {
            return true;
        }
        return false;
    }
}